<template>
    <div class="content-main">
        <div class="breadcrumb">
            <div class="breadcrumb-icon">
                <img src="./../../assets/images/breadcrumb_icon.png" />
            </div>
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/teacher/projectProduction' }">案例制作</el-breadcrumb-item>
                <el-breadcrumb-item>{{projectBreadCrumbBack}} - 制作案例文档</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="content-box">
            <div class="content-title">
                <!-- <img src="./../../assets/images/title_icon13.png" />案例文档 -->
                <div class="content-title-btn-box">
                    <el-button type="primary" @click="addFn">添加</el-button>
                    <el-button type="primary" @click="deleteFn">批量删除</el-button>
                </div>
            </div>
            <div class="common-tool-table">
                <el-table
                :data="tableData"
                ref="multipleTable"
                border
                style="width: 100%"
                @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="100px">
                    </el-table-column>
                    <el-table-column prop="name" label="名称">
                    </el-table-column>
                    <el-table-column prop="gmtModified" label="文件更新时间">
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <a :href="'/dataplatform/common/fileDownload?path='+scope.row.fileName"><el-button type="text">下载</el-button></a>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-size="pagesize"
                    layout="total, prev, pager, next, jumper"
                    :total="totalCount"
                    style="margin-top: 20px; text-align: center;">
                </el-pagination>
            </div>
            <el-dialog class="common-tool-dialog" title="添加文件" :visible.sync="dialogFormVisible" width="500px" @close="closeDialog">
                <el-form :model="form" :rules="rules" ref="form" label-width="100px">
                    <el-form-item label="名称 :" prop="title">
                        <el-input type="text" v-model="form.title" style="width: 80%;" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="版本文件 :" class="version-file">
                        <el-button type="primary">上传文件<input id="version-file-input" type="file" multiple="multiple" auto-complete="off" @change="getFile"></input></el-button>
                        <p v-if="form.versionFile.length>0">已选: {{form.versionFile}}</p>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align:center;">
                    <el-button type="primary" @click="saveForm('form')">保存</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
    import BreadCrumbBack from '@/components/breadCrumbBack.vue'
    export default {
        components: {
            BreadCrumbBack
        },
        data () {
            return {
                projectId: '',
                //面包屑name
                projectBreadCrumbBack: '',
                tableData: [],
                currentPage:1,
                pagesize:10,
                totalCount: 1000,
                multipleSelection: [],
                dialogFormVisible: false,
                fileName: '',
                form: {
                    title: '',
                    versionFile: ''
                },
                rules: {
                    title: [
                        { required: true, message: '请输入名称', trigger: 'blur' }
					],
                    versionFile: [
                        { required: true, message: '请上传版本文件', trigger: 'blur' }
					]
                }
            }
        },
        created () {
            this.projectId = JSON.parse(window.localStorage.getItem('teacher-project-id')).itemId
            this.projectBreadCrumbBack = this.$store.state.projectBreadCrumbBack
            this.init()
        },
        methods: {
            init(){
                let self = this
                self.$http.get('/dataplatform/itemFile/page?pageNum='+self.currentPage+'&pageSize='+self.pagesize+'&itemId='+self.projectId).then(response => {
                    let res = response.data
                    if(res.code == '200'){
                        self.tableData = res.data.list
                        self.totalCount = res.data.total
                    }else if(res.code == '401'){
                        self.$router.replace({
                            path:'/login'
                        })
                    }else{
                        self.$message.error(res.message)
                    }
                })
            },
            //表格分页
			handleSizeChange: function (size) {
				this.pagesize = size;
			},
			handleCurrentChange: function(currentPage) {
				this.currentPage = currentPage
				this.init()
            },
            //全选
			handleSelectionChange(val) {
				let valArr = []
				for(let i = 0; i < val.length; i++){
					valArr.push(val[i].id)
				}
				this.multipleSelection = valArr
            },
            //关闭弹窗
            closeDialog(){
                this.$refs.form.resetFields()
            },
            //添加
            addFn(){
                this.form.title = ''
                this.fileName = ''
                this.form.versionFile = ''
                this.dialogFormVisible = true
            },
            //删除
            deleteFn() {
                let self = this
                if(self.multipleSelection.length == 0){
                    self.$message({
                        message: '请选择要删除的文档',
                        type: 'warning'
                    })
					return
                }
                let ids = ''
				for(let item in self.multipleSelection){
					if(item == 0){
						ids = self.multipleSelection[item]
					}else{
						ids = ids + ',' +self.multipleSelection[item]
                    }
                }
				self.$confirm('是否删除选中?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					self.$http.get('/dataplatform/itemFile/delete?ids='+ids+'').then((response) => {
						let res = response.data;
						if(res.code == '200'){
                            self.$message({
                                message: '删除成功',
                                type: 'success'
                            })
                            self.currentPage = 1
							self.init()
						}else if(res.code == '401'){
                            self.$router.replace({
                                path:'/login'
                            })
                        }else{
                            self.$message.error(res.message)
                        }
					},(err) => {
						console.log('err');
					})
				}).catch(() => {
				})
            },
            //上传文件
            getFile($event) {
                let self = this
                let isLt2M = $event.target.files[0].size / 1024 / 1024 < 500
                let fileType = $event.target.files[0].name
                    fileType = fileType.substring((fileType.lastIndexOf('.') + 1), fileType.length)
                if(!isLt2M){
                    self.$message.error('上传文件大小不能超过 500MB!')
                    return false
                }
                if(fileType != 'docx' && fileType != 'doc' && fileType != 'txt' && fileType != 'xls' && fileType != 'xlsx' && fileType != 'csv' && fileType != 'ppt' && fileType != 'pptx' && fileType != 'zip' && fileType != 'rar' && fileType != 'tar' && fileType != 'pdf'){
                    self.$message.error('不支持此类型文件!')
                    return false
                }

                let fd = new FormData()
                    fd.append('files', $event.target.files[0])
                const loading = this.$loading({
                    lock: true,
                    text: '正在上传中',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                })
                self.$http.post('/dataplatform/common/upload/file',fd, {headers: {'Content-Type': 'multipart/form-data'}}).then(response => {
                    let res = response.data
                    if(res.code == '200'){
                        loading.close()
                        self.$message({
                            message: '上传成功',
                            type: 'success'
                        })
                        self.fileName = res.data[0].fileName
                        self.form.versionFile = $event.target.files[0].name
                    }else if(res.code == '401'){
                        loading.close()
                        self.$router.replace({
                            path:'/login'
                        })
                    }else{
                        loading.close()
                        self.$message.error(res.message)
                    }
                })

            },
            //添加表单提交
            saveForm(form) {
                let self = this
				self.$refs[form].validate((valid) => {
                    if (valid) {
                        self.$http.post('/dataplatform/itemFile/create',{
                            itemId: self.projectId,
                            name: self.form.title,
                            fileName: self.fileName
                        }).then((response) => {
                            let res = response.data
                            if(res.code == '200') {
                                self.$message({
                                    message: '添加成功',
                                    type: 'success'
                                })
                                self.init()
                                self.dialogFormVisible = false
                                $('#version-file-input').val('')
                                self.$refs[form].resetFields()
                            }else if(res.code == '401'){
                                self.$router.replace({
                                    path:'/login'
                                })
                            }else{
                                self.$message.error(res.message)
                            }
                        })
                    }
                })
            }
        }
    }
</script>
